<?php
namespace app\index\model;

use app\common\model\SuperModel;
use app\ux\UtilCurl;
use think\Log;
use think\Request;

class Task extends SuperModel
{

    protected $connection = 'mysql://root:JB6MUn64xICo@rm-bp1h205f36fv8pecto.mysql.rds.aliyuncs.com:3306/dragon#utf8';

    protected function initialize()
    {
        parent::initialize();

        $this->table = 'task';
        $this->logInit('mail');
    }

    /**
     * 发放类型获取器
     *
     * @param    [type] $value [description]
     * @return   [type]
     */
    public function getIssuetypeAttr($value)
    {

        $type = [
            0 => '即时发放',
            1 => '定时发放',
        ];
        return $type[$value];
    }

    /**
     * 角色ID修改器(字符串转整型)
     *
     * @param    string $value 角色ID 字段值
     */
    public function setCharacteridAttr($value)
    {

        return ($value == '全服发放') ? 0 : $value;
    }
    /**
     * 列表(主键列表，条件数组，闭包查询)
     */
    public function doList($param = null)
    {

        $page  = $param['page'];
        $start = $param['start'];
        $limit = $param['limit'];

        $offset = ($page - 1) * $limit;

        //列表参数查询（按发放时间逆序排列）
        $map = [];

        $result = self::all(function ($query) use ($map, $offset, $limit) {
            $query->where($map)
                ->limit($offset, $limit)
                ->order('issue_at desc');
        });

        $rows = [];

        foreach ($result as $data) {

            $item = $data->getData();

            //发放类型获取器转换（整型转字符串）

            $item['issuetype'] = $data->getAttr('issuetype');

            array_push($rows, $item);
        }

        //查询总计
        //
        $total = self::where($map)->count();

        $res = array();

        if ($total > 0) {
            $res['rows']  = $rows;
            $res['total'] = $total;
        } else {
            $res['rows']  = array();
            $res['total'] = 0;
        }

        //返回信息
        //
        return ($res);

    }
    /**
     * 添加全服（定时发放）任务
     *
     * @return   void
     */
    public function addTimingIssueTaskToAll(Request $request)
    {

        $param = $request->param();

        //1 定时发放,完成状态未知

        $param['status'] = -1;

        $res = $this->allowField(true)->save($param);
        return ($res);
    }
    /**
     * 添加全服（即时发放）任务
     *
     * @return   void
     */
    public function addInstantIssueTaskToAll(Request $request)
    {

        // 服务器ID
        $sid = $request->param('server_id');

        $param = $request->param();

        $param['issue_at'] = date("Y-m-d H:i:s");

        //接口请求
        //
        $mail = $request->param('mail_id');
        $cid  = 0;

        $msg = $this->doCurlRequest($sid, $mail, $cid);
        $rtn = json_decode($msg, true);

        //判断接口调用回参
        //
        if (0 == $rtn['code']) {

            $param['complete_at'] = date("Y-m-d H:i:s");
            $param['status']      = 1;

        } else {

            $param['status'] = 0;
        }

        $param['comments'] = $msg;

        $res = $this->allowField(true)->save($param);
        return ($res);
    }
    /**
     * 新增记录
     *
     * @return   void
     */
    public function doAdd(Request $request)
    {

        try {

            // 服务器ID

            $sid = $request->param('server_id');

            //全服发放处理
            //
            if ('全服发放' === $request->param('characterid')) {

                //判断发放类型 0立即发放

                if (0 == $request->param('issuetype')) {

                    $res = $this->addInstantIssueTaskToAll($request);
                    return ($res);

                } else if (1 == $request->param('issuetype')) {

                    $res = $this->addTimingIssueTaskToAll($request);
                    return ($res);
                }
            }

            //单个多个角色ID对象发放处理

            $param = $request->param();

            //判断发放类型 0立即发放

            if (0 == $request->param('issuetype')) {

                $param['issue_at'] = date("Y-m-d H:i:s");

                //获取发放对象字符串,
                //用逗号拆分数组，如果数组的长度为1则单个处理,
                //如果数组的长度大于1则遍历数组元素分开插入。

                $arr = explode(',', $request->param('characterid'));

                if (1 == count($arr)) {

                    //接口请求
                    //
                    $mail = $request->param('mail_id');
                    $cid  = $request->param('characterid');

                    $msg = $this->doCurlRequest($sid, $mail, $cid);
                    $rtn = json_decode($msg, true);

                    //判断接口调用回参
                    //
                    if (0 == $rtn['code']) {

                        $param['complete_at'] = date("Y-m-d H:i:s");
                        $param['status']      = 1;

                    } else {

                        $param['status'] = 0;
                    }

                    $param['comments'] = $msg;

                    $res = $this->allowField(true)->save($param);
                    return ($res);

                } else if (count($arr) > 1) {

                    //多对象发放处理

                    $rows = [];

                    //遍历数组
                    //
                    for ($i = 0; $i < count($arr); $i++) {

                        $mail = $request->param('mail_id');
                        $cid  = $arr[$i];

                        $msg = $this->doCurlRequest($sid, $mail, $cid);
                        $res = json_decode($msg, true);

                        $param['characterid'] = $arr[$i];

                        //判断接口调用回参
                        $row = $param;

                        if (0 == $res['code']) {

                            $row['complete_at'] = date("Y-m-d H:i:s");
                            $row['status']      = 1;

                        } else {
                            $row['status'] = 0;
                        }

                        $row['comments'] = $msg;

                        array_push($rows, $row);

                    }

                    $res = $this->allowField(true)->saveAll($rows);
                    return ($res);
                }

            } else if (1 == input('issuetype')) {

                //1 定时发放,完成状态未知

                $param['status'] = -1;

                $arr = explode(',', input('characterid'));

                if (1 == count($arr)) {

                    $res = $this->allowField(true)->save($param);
                    return ($res);

                } else if (count($arr) > 1) {

                    $rows = [];

                    //遍历数组
                    //
                    for ($i = 0; $i < count($arr); $i++) {

                        $param['characterid'] = $arr[$i];
                        $row                  = $param;

                        array_push($rows, $row);
                    }

                    $res = $this->allowField(true)->saveAll($rows);
                    return ($res);
                }
            }

        } catch (\Exception $e) {

            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 接口请求
     *
     * @param    [type] $mail [description]
     * @param    [type] $cid [description]
     * @return   [array] 接口请求返回
     */
    public function doCurlRequest($server_id, $mail_id, $character_id)
    {

        try {

            $url = $this->getRemoteIssueUrlBySid($server_id);
            $url .= $mail_id . ',' . $character_id;

            $curl = new UtilCurl;
            $rtn  = $curl->get($url);

            return ($rtn);

        } catch (\Exception $e) {

            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 通过服务器ID查询API表获取发放地址
     *
     */
    public function getRemoteIssueUrlBySid($server_id)
    {
        //$record = Apis::getByServerId($server_id);
        //return ($record->mail);
        //
        return ("http://115.239.196.59:19998/?sid=144169&mid=20006&serverid=1&cid=1&webgm_cmd=mail_gift&param=");
    }

    /**
     * 执行定时发放任务
     *
     * @return   [type]
     */
    public function issueMailByAppointedTime()
    {

        //查询未处理的定时发放任务
        //
        $map = [
            'issuetype' => 1, //定期发放标记
            'status'    => -1, //未处理标记
        ];

        $res = self::all($map);

        //处理待发放任务

        $rows = [];

        //遍历待发放邮件
        //
        foreach ($res as $v) {

            $row['id'] = $v['id'];

            //比较发放时间和当前日期时间，
            //如果大于发放时间则立即发放
            //
            if (strtotime(date("Y-m-d H:i:s")) >= strtotime($v['issue_at'])) {

                $character_id = $v['characterid'];
                $mail_id      = $v['mail_id'];
                $server_id    = $v['server_id'];

                $msg = $this->doCurlRequest($server_id, $mail_id, $character_id);
                $res = json_decode($msg, true);

                if (0 == $res['code']) {

                    $row['complete_at'] = date("Y-m-d H:i:s");
                    $row['status']      = 1;

                } else {

                    $row['status'] = 0;
                }

                $row['comments'] = $msg;

                array_push($rows, $row);
            }
        }

        //更新所有定期任务处理记录信息

        $res = $this->allowField(true)->saveAll($rows);
        return $res;
    }

    /**
     * 日志分类位置初始化
     *
     * @return   [type]
     */
    protected function logInit($folder)
    {
        Log::init([
            'type' => 'File',
            'path' => APP_PATH . 'index' . DS . 'logs' . DS . $folder . DS,
        ]);
    }
}
